<?php
/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/
namespace app\admin\controller;

use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\model\Region;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 代理管理
 *
 * @icon fa fa-circle-o
 */
class Proxy extends Backend
{

    /**
     * Proxy模型对象
     * @var \app\admin\model\Proxy
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Proxy;
        $this->view->assign("statusList", $this->model->getStatusList());
    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                if ($row->province){
                    $row->provinceName = Region::where('city_code',$row->province)->value('name');
                }else{
                    $row->provinceName = '';
                }

                if ($row->city){
                    $row->cityName = Region::where('city_code',$row->city)->value('name');
                }else{
                    $row->cityName = '';
                }

                if ($row->district){
                    $row->districtName = Region::where('city_code',$row->district)->value('name');
                }else{
                    $row->districtName = '';
                }

                if ($row->review){
                    $row->reviewer = Admin::where('id',$row->review)->value('username');
                }else{
                    $row->reviewer = '';
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if(\app\admin\model\Proxy::where('user_id',$params['user_id'])->where('status','<>',\app\admin\model\Proxy::STATUS_REJECT)->find()){
                throw new Exception('当前代理已存在，请正确添加');
            }

            if (\app\admin\model\Proxy::where('province',$params['province'])->where('city',$params['city'])->where('status',\app\admin\model\Proxy::STATUS_ENDORSE)->find()){
                throw new Exception('该城市已存在代理');
            }
            $userInfo = $this->auth->getUserInfo();
            $params['create_time'] = time();
            $params['update_time'] = time();
            $params['review'] = $userInfo['id'];
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids=null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $userInfo = $this->auth->getUserInfo();
            $params['review'] = $userInfo['id'];
            $params['update_time'] = time();
            if($params['status'] == \app\admin\model\Proxy::STATUS_ENDORSE){
                if (\app\admin\model\Proxy::where('user_id','<>',$params['user_id'])->where('province',$params['province'])->where('city',$params['city'])->where('status',\app\admin\model\Proxy::STATUS_ENDORSE)->find()){
                    throw new Exception('该城市已存在代理');
                }
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
